package main

import (
	"fmt"
	"html/template"
	"io/ioutil"
	"net/http"
	"os"
)
func GetAllFile(pathname string, s []string) ([]string, error) {
	rd, err := ioutil.ReadDir(pathname)
	if err != nil {
		fmt.Println("read dir fail:", err)
		return s, err
	}

	for _, fi := range rd {
		if !fi.IsDir() {
			fullName := pathname + "/" + fi.Name()
			s = append(s, fullName)
		}
	}
	return s, nil
}
func welcome(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("view/index.html")
	if err != nil {
		fmt.Println(err)
		return
	}
	data := make([]string,0)
	data,_ = GetAllFile("./static/downloads",data)
	fmt.Println(data)
	fmt.Println(len(data))
	t.Execute(w, data) //第二个参数表示向模版传递的数据
}
func play(w http.ResponseWriter, r *http.Request) {
	t, err := template.ParseFiles("view/play.html")
	if err != nil {
		fmt.Println(err)
		return
	}
	file := r.URL.Query().Get("file")
	fmt.Println("file:",file)
	t.Execute(w, file) //第二个参数表示向模版传递的数据
}
func del(w http.ResponseWriter, r *http.Request) {
	file := r.URL.Query().Get("file")
	fmt.Println("file:",file)
	err := os.Remove(file)
	if err != nil {
		w.Write([]byte(err.Error()))
	} else {
		w.Write([]byte("删除成功"))
	}
	return
}
func main() {
	server := http.Server{Addr: ":8090"}
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static"))))
	http.HandleFunc("/", welcome)
	http.HandleFunc("/del", del)
	http.HandleFunc("/play", play)
	fmt.Println("启动成功 端口:8090")
	server.ListenAndServe()
}
